package com.bookmanger.server.service.impl;

import com.bookmanger.server.service.RankingService;
import com.bookmanger.server.mapper.RankingMapper;
import com.bookmanger.pojo.Entity.Borrow;
import com.bookmanger.pojo.Entity.Book;
import com.bookmanger.pojo.Entity.ISBN;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.ArrayList;
import java.util.Collections;

@Service
public class RankingServiceImpl implements RankingService {

    @Autowired
    private RankingMapper rankingMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String BORROW_RANKING_KEY = "borrow_ranking";

    @Override
    public void updateSet(int borrowId) {
        // TODO: 添加借阅记录
        // borrowService.borrowBook(borrowId, managerId);

        // 获取借阅记录
        Borrow borrow = rankingMapper.getBorrowById(borrowId);
        if (borrow == null) {
            throw new RuntimeException("未找到借阅记录");
        }

        // 根据book_id获取书籍信息
        Book book = rankingMapper.getBookById(borrow.getBookId());
        if (book == null) {
            throw new RuntimeException("未找到书籍信息");
        }

        // 根据isbn_id获取ISBN信息
        ISBN isbn = rankingMapper.getIsbnById(book.getIsbnId());
        if (isbn == null) {
            throw new RuntimeException("未找到ISBN信息");
        }

        // 构建存储到Redis中的书籍信息
        Map<String, Object> bookInfo = new HashMap<>();
        bookInfo.put("isbn_id", isbn.getId());
        bookInfo.put("title", isbn.getTitle());
        bookInfo.put("author", isbn.getAuthor());
        
        // 将书籍信息序列化为字符串存储
        String bookInfoStr = isbn.getId() + ":" + isbn.getTitle() + ":" + isbn.getAuthor();

        // 更新Redis排行榜，增加该书籍的借阅次数
        redisTemplate.opsForZSet().incrementScore(BORROW_RANKING_KEY, bookInfoStr, 1.0);
    }

    @Override
    public List<Map<String, Object>> getBorrowRanking() {
        try {
            // 从Redis中获取借阅排行榜，按分数降序排列
            Set<ZSetOperations.TypedTuple<Object>> rankingSet = redisTemplate.opsForZSet()
                    .reverseRangeWithScores(BORROW_RANKING_KEY, 0, 9); // 获取前10名

            if (rankingSet == null || rankingSet.isEmpty()) {
                return Collections.emptyList();
            }

            // 转换为List<Map>格式返回
            List<Map<String, Object>> result = new ArrayList<>();
            for (ZSetOperations.TypedTuple<Object> tuple : rankingSet) {
                Map<String, Object> map = new HashMap<>();
                
                // 解析存储的书籍信息
                String bookInfoStr = (String) tuple.getValue();
                String[] parts = bookInfoStr.split(":", 3);
                
                if (parts.length >= 3) {
                    map.put("isbn_id", Integer.parseInt(parts[0]));
                    map.put("title", parts[1]);
                    map.put("author", parts[2]);
                } else {
                    map.put("title", tuple.getValue());
                }
                
                map.put("borrowCount", tuple.getScore().intValue());
                result.add(map);
            }
            
            return result;
        } catch (Exception e) {
            // 出现异常时返回空列表
            return Collections.emptyList();
        }
    }

    /**
     * 每天凌晨清空排行榜
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void clearRanking() {
        redisTemplate.delete(BORROW_RANKING_KEY);
    }
}